Skip to main content

Loops

Try PowerShell - Keeping you in the loop!

Foreach

The most widely used looping mechanism in PowerShell is the Foreach loop. This is not to be confused with the Foreach-Object which normally appears behind the PowerShell pipeline.

Foreach($i in 1..10){
Write-Output "$i x 12 = $($i * 12)"
}

The example above runs for each item in 1 to 10. It multiplies with 12 and outputs the result on the screen.

While

While loop is useful when you want to create an infinte loop. While loop only runs when the condition returns True. So, you could either enter the loop or skip the loop completely depending on your condition.

While($true){
$Name = Read-Host "Enter your name (Blank to exit)"
If ([String]::IsNullorEmpty($Name)){ break }
Write-Host "Hello $Name"
}

Do While

When you need to run the loop at least once, use the Do While loop. The code block within Do section runs once then the loop checks the while condition. It continues to run while the condition is True.

Do {
$Name = Read-Host "Enter your name"
Write-Host "Hello $Name"
$Answer = Read-Host "Continue (y/n)?"
}
While($Answer.ToLower() -eq 'y')

Do Until

Do Until loop continues to run while the condition is False. The code structure is exactly the same as the Do While loop.

Do {
$Name = Read-Host "Enter your name"
Write-Host "Hello $Name"
$Answer = Read-Host "Continue (y/n)?"
}
Until($Answer.ToLower() -eq 'n')
tip

Remember this: While($true) Until($false)

For

For loop is useful when you know the exact number of time you need to execute your code.

For ($i = 1; $i -le 12; $i++){
Write-Output "$i x 12 = $($i * 12)"
}

The example above runs the for loop. Begining from 1 until it is less than or equal to 12 increment by 1, multiply the value with 12 and outputs the result on the screen.
$i++ means increase the value of the variable i by 1.
$i-- means decrease the value of the variable i by 1.

Recursive

Recursive loop is the loop that calls itself within its own code, function in this case. This kind of loop is rarely used but can be useful for some mathematics computation ie. factorial.

Function Test-StackDepth{
Param($Number = 1)

Write-Output $Number
$Number++
Test-StackDepth $Number
}
Test-StackDepth

You could run the above script and find out where your script stops with the error message "The script failed due to call depth overflow".

caution

Be aware that the recursive loop uses the memory stacks and it will terminate when the stacks are full.